package com.xia.service.impl;

import com.xia.dao.BankInfoDao;
import com.xia.po.BankInfo;
import com.xia.service.BankService;
import com.xia.util.ExcelUtil;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class BankServiceImpl implements BankService {

    @Autowired
    private BankInfoDao bankInfoDao;

    @Autowired
    private ExcelUtil excelUtil;

    @Override
    public boolean addBank(MultipartFile file) throws IOException {

        List<BankInfo> bankList = new ArrayList<>();

        String fileName = file.getOriginalFilename();
        //判断文件类型
        String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
        //获取流
        InputStream fileInputStream = file.getInputStream();

        Workbook workbook = new XSSFWorkbook(fileInputStream);

        //获取第一sheet
        Sheet sheet = workbook.getSheetAt(0);
        int count = 0;
        boolean flag = false;
        if (null != sheet) {
            for (int i = 1; i <= sheet.getLastRowNum(); i++) {
                BankInfo bank = new BankInfo();
                Row row = sheet.getRow(i);
                if (null == row) {
                    continue;
                }


                System.out.println(row.getCell(i)+"---------------");

                //设置数据类型
                row.getCell(0).setCellType(Cell.CELL_TYPE_STRING);
                String name = row.getCell(0).getStringCellValue();

                row.getCell(1).setCellType(Cell.CELL_TYPE_STRING);
                String password = row.getCell(1).getStringCellValue();

                bank.setName(name);
                bank.setCode(password);

                bankList.add(bank);
                count++;

            }

        }
        if (bankList.size() > 0) {
           flag = count ==  bankInfoDao.insertList(bankList);
        }
        return flag;
    }

    @Override
    public void insertList(MultipartFile file) throws IOException {
        List<BankInfo> dtoList = excelUtil.readExcelFileToDTO(file, BankInfo.class);
        System.out.println("-----------");
        System.out.println("00000000000000");
        bankInfoDao.insertList(dtoList);
    }
}
